<template>
	<view class="main--height">
		<view class="head" :style="{marginTop:(titleHeight+3)+'px'}">
			<uv-tabs :list="tablist" lineWidth="48" lineHeight="5" lineColor="#FF97A8" :activeStyle="{
						color: '#303133',
						fontWeight: 'bold',
						fontSize:'48rpx',
			    	}" :inactiveStyle="{
						color: '#222',
						fontSize:'36rpx',
					}" itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;" @click="tabclick"></uv-tabs>
			<view class="message-item padding_30" v-if="currentIndex==0">
				<!-- <TUIConversation></TUIConversation> -->
				<!-- <button @click="openConversationList">打开会话列表</button> -->
				<chatFriendNotice></chatFriendNotice>
				<chatMessageNotice></chatMessageNotice>
				<view class="chat-list">
					<view v-for="(item,index) in conversationList" :key="index">
						<view class="chat-item" v-if="item.type=='C2C'"
							@click="toChat(item.conversationID,item.userProfile.userID)">
							<!-- <image v-if="item.userProfile.avatar==''"
								src="https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_21.png"
								mode="aspectFill"></image> -->
							<view>
								<image :src="item.userProfile.avatar" mode="aspectFill"></image>
							</view>
							<view class="chat-info">
								<view class="chat-name">
									{{item.userProfile.nick}}
								</view>
								<view class="chat-content text-cut">
									{{item.lastMessage.messageForShow}}
								</view>
							</view>
							<view class="chat-state">
								<view class="chat-time" v-if="item.lastMessage.lastTime!=0">
									{{formatTime(item.lastMessage.lastTime)}}
								</view>
								<!-- <view class="unreadCount"> -->
								<uv-badge type="error" max="99" :value="item.unreadCount"></uv-badge>
								<!-- </view> -->
							</view>
						</view>
						<view class="chat-item" v-if="item.type=='GROUP'" @click="toGroup(item.conversationID)">
							<view @click="toGroupPage(item.groupProfile.groupID)">
								<image v-if="item.groupProfile.avatar==''" src="@/static/images/talk.png"
									mode="aspectFill"></image>
								<image v-else :src="item.groupProfile.avatar" mode="aspectFill"></image>
							</view>
							<view class="chat-info">
								<view class="chat-name">
									{{item.groupProfile.name}}
								</view>
								<view class="chat-content text-cut">
									{{item.lastMessage.messageForShow}}
								</view>
							</view>
							<view class="chat-state">
								<view class="chat-time">
									{{formatTime(item.lastMessage.lastTime)}}
								</view>
								<!-- <view class="unreadCount"> -->
								<uv-badge type="error" max="99" :value="item.unreadCount"></uv-badge>
								<!-- </view> -->
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="friend-item padding_30" v-if="currentIndex==1">
				<view @click="toSearchPage">
					<uv-input placeholder="搜索好友、群聊" prefixIcon="search" shape="circle"
						prefixIconStyle="font-size: 22px;color: #909399" clearable disabled></uv-input>
				</view>
				<scroll-view scroll-y="true" style="height: 78vh;" @scrolltolower="scrollPage">
					<view class="friend-list" v-for="(item,index) in friendList" :key="item.id">
						<view @click="toUserPage(item.id)">
							<image v-if="item.avatar!=''" :src="baseurl + '/' +item.avatar" mode="aspectFill"></image>
							<image v-else src="@/static/images/avatar.png" mode="aspectFill"></image>
						</view>
						<text class="nickname">{{item.username}}</text>
						<text class="chat-btn" @click="toChat(`C2C${item.id}`,item.id)">私信</text>
					</view>
				</scroll-view>
			</view>
			<view class="friend-item padding_30" v-if="currentIndex==2">
				<view @click="toSearchPage">
					<uv-input placeholder="搜索好友、群聊" prefixIcon="search" shape="circle"
						prefixIconStyle="font-size: 22px;color: #909399" clearable disabled></uv-input>
				</view>
				<scroll-view scroll-y="true" style="height: 78vh;" @scrolltolower="scrollPage2">
					<view class="friend-list" v-for="(item,index) in chatRoomList" :key="item.id">
						<view class="group-avatar" @click="toGroupPage(item.id)">
							<image class="base-avatar" src="@/static/images/talk.png" mode="aspectFill"></image>
							<!-- <image class="overlay-avatar" src="../../static/images/banner.png" mode="aspectFill"> -->
							<!-- </image> -->
						</view>
						<text class="nickname">{{item.chat_title}}</text>
						<text class="chat-btn" @click="toGroupChat(item)">进群</text>
						<text class="chat-btn" v-if="userId==item.user_id" @click="dissolution(item,index)">解散</text>
						<!--  v-if="userId==item.user_id" -->
					</view>
				</scroll-view>
			</view>
		</view>
		<tabbar :current="3"></tabbar>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onReachBottom
	} from "@dcloudio/uni-app"
	import {
		onMounted,
		reactive,
		ref,
		inject,
		getCurrentInstance
	} from 'vue';
	import {
		getFriendListAPI,
		getChatRoomListAPI,
		deleteChat
	} from '@/api/chat.js'
	import {
		throttle,
		formatTime
	} from "../../utils/utils";
	import {
		useUserStore
	} from '@/store/modules/user.js'
	import TencentCloudChat from "@tencentcloud/chat";
	import tabbar from '@/components/tabbar/tabbar' //引用组件中的tabbar
	// import TUIConversation from "@/TUIKit/components/TUIConversation/index"
	import chatFriendNotice from '@/components/chatFriendNotice.vue'
	import chatMessageNotice from '@/components/chatMessageNotice.vue'
	const {
		proxy
	} = getCurrentInstance();
	const userstore = useUserStore()
	const tablist = reactive([{
			name: '消息'
		},
		{
			name: '好友'
		},
		{
			name: '活动碰头'
		}
	])
	const currentIndex = ref(0)
	const titleHeight = ref(0)
	const conversationList = ref([])
	const friendList = ref([])
	const total = ref(0)
	const page = ref(1)
	const chatRoomList = ref([])
	const roomPage = ref(1)
	const roomTotal = ref(0)
	const baseurl = ref('')
	const userId = ref('')
	const chat2 = inject('$chat')
	onMounted(() => {
		// #ifdef MP-WEIXIN
		let res = uni.getMenuButtonBoundingClientRect();
		titleHeight.value = res.top
		// #endif
	})
	onLoad(() => {
		baseurl.value = uni.getStorageSync('baseUrl')
		openConversationList()
		getFriendList()
		getChatRoomList()
		UserInfo()
	})

	const UserInfo = async () => {
		
		let res = await userstore.getUserInfo()
		if (res.code == 200) {
			userId.value = res.data.id
			console.log(userId.value, '...................................')
		}
	}
	const tabclick = (e) => {
		currentIndex.value = e.index
		if (currentIndex.value == 1) {
			page.value = 1
			friendList.value = []
			getFriendList()
		} else if (currentIndex.value == 2) {
			roomPage.value = 1
			chatRoomList.value = []
			getChatRoomList()
		}
	}
	const openConversationList = () => {
		let promise = chat2.chat.getConversationList();
		promise.then(function(imResponse) {
			// 全量的会话列表，用该列表覆盖原有的会话列表
			conversationList.value = imResponse.data.conversationList;
			console.log(conversationList.value, '-=========')
			// 从云端同步会话列表是否完成
			const isSyncCompleted = imResponse.data.isSyncCompleted;
		}).catch(function(imError) {
			// 获取会话列表失败的相关信息
			console.warn('getConversationList error:', imError);
		});
		// 监听会话更新
		let onConversationListUpdated = function(event) {
			conversationList.value = event.data
			// console.log(conversationList.value)
		};
		chat2.chat.on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, onConversationListUpdated);
	}
	// 单聊
	const toChat = (conversationID, userId) => {
		uni.navigateTo({
			url: `/TUIKit/components/TUIChat/index?conversationID=${conversationID}` + '&userId=' + userId
		});
	}
	// 群聊
	const toGroup = (conversationID) => {

		uni.navigateTo({
			url: `/TUIKit/components/TUIChat/index?conversationID=${conversationID}`
		});
	}
	// 去群聊主页
	const toGroupPage = (id) => {
		// console.log(id)
		uni.navigateTo({
			url: '/pages/chat/grouppage/index?groupId=' + id
		})
	}
	const toGroupChat = (item) => {
		
		// 搜索群是否存在
		let promise = chat2.chat.searchGroupByID(item.id + '');
		promise.then(function(imResponse) {
			const group = imResponse.data.group; // 群组信息
			let join = chat2.chat.joinGroup({
				groupID: group.groupID,
				type: TencentCloudChat.TYPES.GRP_PUBLIC
			});
			// console.log(imResponse, '搜索该群')
			join.then(function(res) {
				// console.log(res, '=============')
				switch (res.data.status) {
					case TencentCloudChat.TYPES.JOIN_STATUS_WAIT_APPROVAL: // 等待管理员同意
						break;
					case TencentCloudChat.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
						// console.log(res.data.group, '加入成功'); // 加入的群组资料
						uni.navigateTo({
							url: `/TUIKit/components/TUIChat/index?conversationID=GROUP${res.data.group.groupID}&type=1`
						});
						break;
					case TencentCloudChat.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
						uni.navigateTo({
							url: `/TUIKit/components/TUIChat/index?conversationID=GROUP${group.groupID}&type=1`
						});
						break;
					default:
						break;
				}
			}).catch(function(imError) {
				console.warn('joinGroup error:', imError); // 申请加群失败的相关信息
				uni.$uv.toast('加入群聊失败')
			});
		}).catch(function(imError) {
			uni.$uv.toast('该群不存在或已被群主解散')
			console.warn('searchGroupByID error:', imError); // 搜素群组失败的相关信息
		});

	}
	// 好友列表上拉加载更多
	const scrollPage = () => {
		if (friendList.value.length >= total.value) {
			uni.showToast({
				title: "没有更多了",
				icon: "none",
				mask: true,
				duration: 800
			})
			return
		}
		page.value++

		uni.showLoading({
			title: "正在加载...",
			mark: true
		})
		getFriendList()
	}
	// 活动碰头列表上拉加载更多
	const scrollPage2 = () => {
		if (chatRoomList.value.length >= total.value) {
			uni.showToast({
				title: "没有更多了",
				icon: "none",
				mask: true,
				duration: 800
			})
			return
		}
		page.value++

		uni.showLoading({
			title: "正在加载...",
			mark: true
		})
		getChatRoomList()
	}
	// 获取好友列表
	const getFriendList = async () => {
		let res = await getFriendListAPI({
			page: page.value
		})
		if (res.code == 200 && res.data) {
			uni.hideLoading()
			total.value = res.data.total
			friendList.value = friendList.value.concat(res.data.data)
		} else {
			uni.hideLoading()
		}
	}
	// 获取活动碰头列表
	const getChatRoomList = async () => {
		let res = await getChatRoomListAPI({
			page: roomPage.value
		})

		if (res.code === 200 && res.data) {
			uni.hideLoading()
			roomTotal.value = res.data.total

			// 原始群聊列表	
			const originalList = res.data.data

			// 用 Promise.all 来并发检查所有群是否存在
			const filteredList = await Promise.all(
				originalList.map(async (item) => {
					try {
						const result = await chat2.chat.searchGroupByID(item.id + '')
						console.log(333, result);
						// 假设 result 表示群存在的标志，例如 result.code === 200 或 result.exists === true
						return item
					} catch (error) {
						// 请求失败或群不存在，则过滤掉
						return null
					}
				})
			)

			// 过滤掉 null，得到真正存在的群聊
			const finalList = filteredList.filter(Boolean)

			chatRoomList.value = chatRoomList.value.concat(finalList)

		} else {
			uni.hideLoading()
		}
	}
	// const getChatRoomList = async () => {
	// 	let res = await getChatRoomListAPI({
	// 		page: roomPage.value
	// 	})
	// 	if (res.code == 200 && res.data) {
	// 		uni.hideLoading()
	// 		console.log(222,res.data);
	// 		roomTotal.value = res.data.total
	// 		chatRoomList.value = chatRoomList.value.concat(res.data.data)
	// 	} else {
	// 		uni.hideLoading()
	// 	}
	// }
	const PostdeleteChat = async (e, index) => {
		let res = await deleteChat({
			user_activity_id: e
		})
		if (res.code == 200 && res.data) {
			chatRoomList.value.splice(index, 1)
		}
	}

	// 搜索
	const toSearchPage = () => {
		uni.navigateTo({
			url: '/pages/chat/searchfriend/index'
		})
	}
	const dissolution = (item, index) => {
		uni.showModal({
			title: '提示',
			content: '解散群聊后无法恢复！是否确认？',
			success: function(res) {
				if (res.confirm) {
					let promise = chat2.chat.searchGroupByID(item.id + '');
					promise.then(function(imResponse) {
						const group = imResponse.data.group; // 群组信息
						dissolution2(group.groupID, item.id, index)
					}).catch(function(imError) {
						uni.$uv.toast('该群不存在或已被群主解散')
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	const dissolution2 = (groupID, itemId, index) => {
		let promise = chat2.chat.dismissGroup(groupID + '');
		promise.then(function(imResponse) { // 解散成功
			PostdeleteChat(itemId, index)
		}).catch(function(imError) {
			console.warn('dismissGroup error:', imError); // 解散群组失败的相关信息
		});
	}

	// 去主页
	const toUserPage = (userId) => {
		uni.navigateTo({
			url: '/pages/user/userpage/index?userId=' + userId
		})
	}
</script>

<style lang="scss" scoped>
	.head {
		height: calc(3rpx + var(--status-bar-height));
	}

	.friend-item {
		.friend-list {
			display: flex;
			align-items: center;
			justify-content: flex-start;
			margin-top: 40rpx;

			image {
				border-radius: 50%;
				width: 100rpx;
				height: 100rpx;
			}

			.group-avatar {
				// position: relative;

				.base-avatar {
					border-radius: 50%;
					width: 100rpx;
					height: 100rpx;
				}

				// .overlay-avatar {
				// 	position: absolute;
				// 	top: 10px;
				// 	left: 10px;
				// 	width: 70rpx;
				// 	height: 70rpx;
				// 	border-radius: 50%;
				// }
			}

			.nickname {
				flex: 1;
				padding-left: 48rpx;
				font-weight: 400;
				font-size: 32rpx;
				color: #222222;
			}

			.loginout {
				font-weight: 400;
				font-size: 28rpx;
				color: #999999;
			}

			.chat-btn {
				width: 116rpx;
				height: 64rpx;
				background: #F6F6F6;
				border-radius: 30rpx;
				font-weight: bold;
				font-size: 28rpx;
				color: #666666;
				line-height: 64rpx;
				text-align: center;
				margin-left: 10rpx;
			}
		}
	}

	// 会话列表
	.chat-list {
		padding: 0rpx 24rpx 24rpx 24rpx;

		.chat-item {
			display: flex;
			align-items: center;
			padding: 20rpx 0;

			image {
				border-radius: 50%;
				width: 100rpx;
				height: 100rpx;
			}

			.chat-info {
				flex: 1;
				margin-left: 24rpx;

				.chat-name {
					font-weight: 400;
					font-size: 32rpx;
					color: #222222;
				}

				.chat-content {
					width: 400rpx;
					padding: 4rpx 0;
					font-weight: 400;
					font-size: 28rpx;
					color: #999999;
				}
			}

			.chat-state {
				display: flex;
				flex-direction: column;
				align-items: flex-end;

				.chat-time {
					font-weight: 400;
					font-size: 24rpx;
					color: #999999;
				}

				.unreadCount {
					width: 55rpx;
					height: 32rpx;
					padding: 4rpx 0;
				}
			}
		}
	}
</style>